# -*- coding: utf-8 -*-

import json
import logging

from django.views.generic import TemplateView
from django.utils.encoding import smart_unicode
from django.utils.decorators import method_decorator
from django.views.decorators.http import require_GET, require_POST

from common.cache import redis_cache
from common.pay.handler import pay_after_recharge
from common.recharge import db as recharge_db
from common.recharge import handler as recharge_handler
from common.utils.tz import utc_to_local_str
from common.utils.decorator import response_wrapper
from common.utils.api import token_required, check_params
from common.utils.export import redirect_to_file, gen_filename

_LOGGER = logging.getLogger(__name__)


class RechargeView(TemplateView):

    def get(self, req):
        query_dct = req.GET.dict()
        export = query_dct.pop('$export', None)
        if export:
            filename = gen_filename('recharge_records')
            cn_header = [
                u'充值单号', u'用户ID', u'充值方式', u'充值状态', u'充值金额', u'申请时间', u'更新时间', u'打款人账号', u'收款账号', u'受理人ID']
            data = recharge_db.export_recharge_records(query_dct)
            return redirect_to_file(data, cn_header, filename)
        items, total_count = recharge_db.list_applys(query_dct)

        resp_items = []
        for item in items:
            data = item.as_dict()
            data['id'] = str(data['id'])
            data['created_at'] = utc_to_local_str(data['created_at'])
            data['updated_at'] = utc_to_local_str(data['updated_at'])
            data['recharger_info'] = json.loads(data['recharger_info'] or '{}')
            data['rechargee_info'] = json.loads(data['rechargee_info'] or '{}')
            resp_items.append(data)

        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'size': len(resp_items), 'total_count': total_count}

    def post(self, req):
        query_dct = json.loads(smart_unicode(req.body))
        user_id = int(query_dct['user_id'])
        recharge_type = int(query_dct['recharge_type'])
        recharger_info = query_dct['recharger_info']
        rechargee_info = query_dct['rechargee_info']
        recharge_handler.apply_recharge(user_id, recharge_type, recharger_info, rechargee_info)
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(RechargeView, self).dispatch(*args, **kwargs)


class SingleRechargeView(TemplateView):

    def get(self, req, apply_id):
        item = recharge_db.get_apply(int(apply_id))
        data = item.as_dict()
        data['id'] = str(data['id'])
        data['created_at'] = utc_to_local_str(data['created_at'])
        data['updated_at'] = utc_to_local_str(data['updated_at'])
        data['recharger_info'] = json.loads(data['recharger_info'] or '{}')
        data['rechargee_info'] = json.loads(data['rechargee_info'] or '{}')
        return data

    def post(self, req, apply_id, pay_amount):
        pay = recharge_handler.finish_apply(req.user_id, apply_id, float(pay_amount))
        try:
            pay_after_recharge(pay, True)
        except Exception as e:
            _LOGGER.exception('admin single recharge, pay_after_recharge of pay[%s] exception.(%s)', pay.id, e)
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(SingleRechargeView, self).dispatch(*args, **kwargs)


class RechargeWechatView(TemplateView):

    def get(self, req):
        query_dct = req.GET.dict()
        items = redis_cache.get_recharge_wechat()
        total_count = len(items)
        resp_items = []
        for item in items:
            resp_items.append(json.loads(item))

        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'size': len(resp_items), 'total_count': total_count}

    # def post(self, req):
    #     item_list = json.loads(smart_unicode(req.body))
    #     update_list = []
    #     for item in item_list:
    #         update_list.append(json.dumps(item, ensure_ascii=False))
    #     redis_cache.set_recharge_wechat(*update_list)
    #     return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(RechargeWechatView, self).dispatch(*args, **kwargs)


@require_POST
@response_wrapper
@token_required
def revert_apply(req, apply_id):
    recharge_db.revert_apply(req.user_id, apply_id)
    return {}


@require_GET
@response_wrapper
@token_required
def get_self_recharge(req):
    on = redis_cache.get_self_recharge()
    return {'on': on}


@require_POST
@response_wrapper
@token_required
def set_self_recharge(req, status):
    redis_cache.set_self_recharge(int(status))
    return {}
